const connection = require('../app/database')

class MomentService {

  // 创建一条动态
  async create(content, userId) {
    try {
      const statement = `insert into moment (content, userId) values (?, ?)`
      const result = await connection.execute(statement, [content, userId])
      return result[0]
    } catch (error) {
      console.log(error)
    }
  }

  // 获取一条动态
  async getMomentById(momentId) {
    try {
      const statement = `
      select m.id momentId, m.content content, m.createAt createAt,
      JSON_ARRAYAGG(mp.url) pic,
      JSON_OBJECT (
          'id',
          u.id,
          'nickname',
          u.nickname,
          'sex',
          ud.sex,
          'avatar',
          u.avatar,
          'wall',
          ud.wall,
          'createAt',
          u.createAt,
          'updateAt',
          u.updateAt
        ) 'user'
      from moment m
      left join user u on m.userId = u.id
      left join user_desc ud on m.userId = ud.userId
      left join moment_pic mp on m.id = mp.momentId
      where m.id = ?`
      const result = await connection.execute(statement, [momentId])
      return result[0][0] || {}
    } catch (error) {
      console.log(error)
    }
  }

  // 获取动态列表
  async getMomentList(pageNo, pageSize) {
    try {
      const statement = `
    select if(count(m.id),JSON_ARRAYAGG(JSON_OBJECT(
      'momentId',
      m.id,
      'content',
      m.content,
      'createAt',
      m.createAt,
      'pic',
      (select if(count(mp.url), JSON_ARRAYAGG(mp.url), null) from moment_pic mp where m.id = mp.momentId),
      'user',
      JSON_OBJECT (
        'id',
        u.id,
        'nickname',
        u.nickname,
        'sex',
        ud.sex,
        'avatar',
        u.avatar,
        'wall',
        ud.wall,
        'createAt',
        u.createAt,
        'updateAt',
        u.updateAt
      )
    )), null) list,
    count(m.id) total
    from moment m
    left join user u on m.userId = u.id
    left join user_desc ud on m.userId = ud.userId
    order by m.id desc
    limit ?, ?`
      const result = await connection.execute(statement, [((pageNo - 1) * pageSize) + '', (pageNo * pageSize) + ''])
      return result[0][0] || {}
    } catch (error) {
      console.log(error)
      throw new Error("报错了")
    }
  }

  // 验证一条动态权限
  async getMomentByIdAndUserId(momentId, userId) {
    try {
      const statement = `select * from moment where id = ? and userId = ?`
      const result = await connection.execute(statement, [momentId, userId])
      return result[0][0] || {}
    } catch (error) {
      console.log(error)
    }
  }

  // 删除一条动态
  async deleteMomentById(momentId) {
    try {
      const statement = `delete from moment where id = ?`
      const result = await connection.execute(statement, [momentId])
      return result[0]
    } catch (error) {
      console.log(error)
    }
  }

}

module.exports = new MomentService
